package com.jackrain.clouddata.oms.dao;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.parser.Feature;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.util.TypeUtils;
import com.jackrain.clouddata.sys.sender.BackSender;
import com.jackrain.nea.core.db.Tools;
import com.jackrain.nea.exception.NDSException;
import com.jackrain.nea.web.query.QueryEngine;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

/**
 * by bigzhi
 */

@Component
@Transactional
public class UploadRetailDao {

    public void insertRetail(JSONObject retailJsonObject, String tag, String topic){
        String clientIdSql = "SELECT AD_CLIENT_ID FROM OMS_TAG WHERE ISACTIVE='Y' AND TAGNAME = ?";
        JSONObject clientJson = QueryEngine.getInstance().doQueryObject(clientIdSql,new Object[]{tag});
        if (clientJson == null){
            throw new NDSException("公司ID未找到!");
        }
        Long clientId = clientJson.getLong("AD_CLIENT_ID");

        String retailTableName = retailJsonObject.getString("name");
        JSONObject retailValueJson = retailJsonObject.getJSONObject("value");
        JSONArray itemArray = retailJsonObject.getJSONArray("item");

        JSONObject omsRetailJson = JSON.parseObject(JSON.toJSONString(retailValueJson,new SerializerFeature[]{SerializerFeature.WriteMapNullValue}), Feature.OrderedField);

        for (int l = 0; l < omsRetailJson.keySet().size(); l++) {
            String key = (String) omsRetailJson.keySet().toArray()[l];
            if (key.contains("DATE") && omsRetailJson.get(key) != null) {
                omsRetailJson.put(key, TypeUtils.castToDate(omsRetailJson.get(key)));
            }
        }
//        omsRetailJson.put("MODIFIEDDATE",new Timestamp(System.currentTimeMillis()));
        omsRetailJson.put("AD_CLIENT_ID",clientId);
        omsRetailJson.put("ID", Tools.getSequence(retailTableName));  //ID

        //生成insertRetSaleSql语句
        StringBuffer insertRetailSql = new StringBuffer( "INSERT INTO "+retailTableName+ "(" );//insertRetSaleSql语句
        StringBuffer q = new StringBuffer();//占位符？
        for (String s:omsRetailJson.keySet()) {
            if(s.equals("ID")){
                q.append( "?" );
                insertRetailSql.append( s +") VALUES(" + q.toString() + ")" );
//                insertRetailSql.append( s );
//                insertRetailSql.append( ") VALUES(" );
//                insertRetailSql.append( q.toString() );
//                insertRetailSql.append( ")" );
            }else{
                insertRetailSql.append( s );
                insertRetailSql.append( "," );
                q.append( "?," );
            }
        }
        //插主表，单条
        QueryEngine.getInstance().executeUpdate(insertRetailSql.toString(), omsRetailJson.values().toArray());

        if(itemArray !=null && itemArray.size() > 0){
            String insertItemSql = null;
            for(int j=0; j<itemArray.size(); j++){
                JSONArray insertItemArray = new JSONArray();

                JSONObject itemJson = itemArray.getJSONObject(j);
                String itemTableName = itemJson.getString("name");
                JSONArray itemValueArray = itemJson.getJSONArray("value");

                if(itemValueArray != null && itemValueArray.size() > 0){
                    //插子表
                    boolean insertItem = false;
                    for(int k=0; k<itemValueArray.size(); k++){
                        JSONObject itemValueJson = itemValueArray.getJSONObject(k);
                        JSONObject omsItemJson = JSON.parseObject(JSON.toJSONString(itemValueJson,new SerializerFeature[]{SerializerFeature.WriteMapNullValue}), Feature.OrderedField);

                        for (int l = 0; l < omsItemJson.keySet().size(); l++) {
                            String key = (String) omsItemJson.keySet().toArray()[l];
                            if (key.contains("DATE") && omsItemJson.get(key) != null) {
                                omsItemJson.put(key, TypeUtils.castToDate(omsItemJson.get(key)));
                            }
                        }
//                        omsItemJson.put("MODIFIEDDATE",new Timestamp(System.currentTimeMillis()));
                        omsItemJson.put("AD_CLIENT_ID",clientId);
                        omsItemJson.put("ID", Tools.getSequence(itemTableName));  //ID

                        //生成insertItemSql语句
                        if(!insertItem) {
                            StringBuffer sb = new StringBuffer( "INSERT INTO "+itemTableName+ "(" );//insertItemSql语句
                            StringBuffer iq = new StringBuffer();//占位符？
                            for (String s:omsItemJson.keySet()) {
                                if(s.equals("ID")){
                                    iq.append( "?" );
                                    sb.append( s );
                                    sb.append( ") VALUES(" );
                                    sb.append( iq.toString() );
                                    sb.append( ")" );
                                }else{
                                    sb.append( s );
                                    sb.append( "," );
                                    iq.append( "?," );
                                }
                            }
                            insertItemSql = sb.toString();
                            insertItem = true;
                        }

                        insertItemArray.set(k,omsItemJson);
                    }

                    //插子表，批量
                    QueryEngine.getInstance().executeBatchUpdate(insertItemSql,insertItemArray);//批量插入子表
                }
            }
        }

        BackSender.send(topic,tag,clientId.toString(),omsRetailJson.getString("BILLNO"));
    }
}
